<script setup lang="ts">
import { ref } from 'vue'
import { useMemberStore, useDeviceStore } from '@/stores'
import { bindDeviceApi } from '@/services/my'
import { onLoad, onUnload, onPullDownRefresh } from '@dcloudio/uni-app'
const memberStore = useMemberStore()
const deviceStore = useDeviceStore()
//蓝牙连接
const btdevicelist = ref<{ name: string }[]>([])
const deviceId = ref('')
const props = defineProps<{
  type: string
}>()
const isCreateBLEConnection = ref(false)
onLoad(() => {
  openBluetoothAdapter()
})

//初始化蓝牙模块
const openBluetoothAdapter = () => {
  //console.log('初始化蓝牙模块')
  uni.openBluetoothAdapter({
    success: (success) => {
      console.log(success + '蓝牙初始化成功')
      startBluetoothDevicesDiscovery()
    },
    fail: (err) => {
      uni.showToast({
        title: '蓝牙功能开启失败，请打开蓝牙重试！',
        icon: 'none',
        duration: 1000,
      })
      uni.onBluetoothAdapterStateChange((res) => {
        if (res.available) {
          startBluetoothDevicesDiscovery()
        }
      })
    },
  })
}
//蓝牙搜索附近设备
const startBluetoothDevicesDiscovery = () => {
  uni.startBluetoothDevicesDiscovery({
    allowDuplicatesKey: false,
    success: (res) => {
      console.log(res + '蓝牙开始搜索')
      onBluetoothDeviceFound()
      console.log(btdevicelist.value)
    },
    fail: (err) => {
      console.log(err + '蓝牙搜索失败')
    },
  })
}
//监听获取新蓝牙设备事件
const onBluetoothDeviceFound = () => {
  uni.onBluetoothDeviceFound((res) => {
    //console.log(res , '监听获取新蓝牙设备事件')
    res.devices.forEach((item) => {
      //设备名称是大写SC开头的，使用正则表达式匹配
      if (/^SC/.test(item.name)) {
        deviceId.value = item.deviceId
        btdevicelist.value.push({ name: item.name })
      }
    })
  })
}

//获取蓝牙设备列表
const getBluetoothDevices = () => {
  console.log('获取蓝牙搜索到的设备列表')
  uni.getBluetoothDevices({
    success: (res) => {
      res.devices.forEach((item) => {
        //设备名称是大写SC开头的，使用正则表达式匹配
        if (/^SC/.test(item.name)) {
          if (btdevicelist.value.length > 0) {
            btdevicelist.value.forEach((i) => {
              if (i.name === item.name) {
                return
              }
            })
          }
          btdevicelist.value.push({ name: item.name })
        }
        console.log(btdevicelist.value)
      })
    },
    fail: (err) => {
      console.log(err)
    },
  })
}
//蓝牙设备连接
const createBLEConnection = (deviceId: string) => {
  console.log('蓝牙设备连接')
  uni.createBLEConnection({
    deviceId,
    success: (res) => {
      console.log('蓝牙设备连接成功', res)
      isCreateBLEConnection.value = true
      getBLEDeviceServices(deviceId)
    },
    fail: (err) => {
      console.log(err + '蓝牙设备连接失败')
    },
  })
}
//获取蓝牙的所有服务
const getBLEDeviceServices = (deviceId: string) => {
  console.log('获取蓝牙的所有服务')
  uni.getBLEDeviceServices({
    deviceId,
    success: (res) => {
      console.log(res)
      res.services.forEach((item) => {
        if (item.uuid === '00001801-0000-1000-8000-00805F9B34FB') {
          getBLEDeviceCharacteristics(deviceId, item.uuid)
        }
      })
    },
    fail: (err) => {
      console.log(err)
    },
  })
}
//获取蓝牙设备某个服务中的所有特征值
const getBLEDeviceCharacteristics = (deviceId: string, serviceId: string) => {
  console.log('获取蓝牙设备某个服务中的所有特征值')
  uni.getBLEDeviceCharacteristics({
    deviceId,
    serviceId,
    success: (res) => {
      console.log(res, '获取特征成功')
      res.characteristics.forEach((item) => {
        if (item.properties.notify || item.properties.indicate) {
          console.log('可以设备接受数据')
          notifyBLECharacteristicValueChange(deviceId, serviceId, item.uuid)
        }
      })
    },
    fail: (err) => {
      console.log(err)
    },
  })
}
//接受设备数据
const notifyBLECharacteristicValueChange = (deviceId: string, serviceId: string, characteristicId: string) => {
  uni.notifyBLECharacteristicValueChange({
    deviceId,
    serviceId,
    characteristicId,
    state: true,
    success: (res) => {
      console.log(res)
      //监听设备发送数据
      uni.onBLECharacteristicValueChange((res) => {
        console.log(res)
      })
    },
    fail: (err) => {
      console.log(err)
    },
  })
}
//定时关闭蓝牙
const timeoutId = setTimeout(() => {
  if (isCreateBLEConnection.value) {
    return
  }
  uni.closeBluetoothAdapter({
    success: (res) => {
      clearTimeout(timeoutId)
      console.log(res)
    },
    fail: (err) => {
      console.log(err)
    },
  })
}, 120000)

//处理点击设备
const handleClick = (deviceNum: string) => {
  if (props.type === 'bind') {
    binddevice(deviceNum)
  } else if (props.type === 'calibrate') {
    createBLEConnection(deviceId.value)
    /* uni.navigateTo({
      url: `/pages/calibrate-equipment/calibrate-equipment?deviceNum=${deviceNum}`,
    }) */
  }
}

//绑定设备
const binddevice = async (deviceNum: string) => {
  const mes = await bindDeviceApi({
    bindFlg: 1,
    deviceNum,
    userId: memberStore.profile!.id,
  })
  console.log(mes)
  if (mes.msg === '对象正常') {
    uni.showToast({
      title: '绑定成功',
      icon: 'none',
      duration: 3000,
    })
    uni.navigateBack({
      delta: 1,
    })
    //修改store中的设备列表
    await deviceStore.getDeviceList()
    //请求设备实时数据
    await deviceStore.getDeviceData()
  } else {
    uni.showToast({
      title: '绑定失败',
      icon: 'none',
      duration: 1000,
    })
  }
}
onUnload(() => {
  uni.closeBluetoothAdapter({
    success: (res) => {
      clearTimeout(timeoutId)
      console.log(res)
    },
    fail: (err) => {},
  })
})
onPullDownRefresh(() => {
  console.log('下拉刷新了')
  uni.stopPullDownRefresh()
})
</script>
<template>
  <view class="content">
    <view class="title">已搜寻到以下设备</view>
    <view class="remind">(下滑画面重新搜索) </view>
    <view class="device-item" v-for="(item, index) in btdevicelist" :key="index" @click="handleClick(item.name)"
      >{{ item.name }}
    </view>
  </view>
</template>
<style lang="scss">
page {
  height: 100vh;
  .content {
    display: flex;
    flex-direction: column;
    .title {
      padding-bottom: 19.231rpx;
      margin-left: 28.846rpx;
      font-size: 46.154rpx;
    }
    .remind {
      font-size: 28.846rpx;
      margin-left: 28.846rpx;
      color: #999999;
      margin-bottom: 28.846rpx;
    }
    .device-item {
      width: 90%;
      height: 86.538rpx;
      line-height: 86.538rpx;
      margin: 0 auto 9.615rpx;
      padding-left: 19.231rpx;
      background-color: #f4f3f8;
    }
  }
}
</style>
